package com.nali.dal.statement.function.formatter;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;

import com.nali.dal.statement.function.DataHandler;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionException;
import com.nali.dal.statement.function.NumberOperater;

/**
 * Decode<br>&nbsp;
 * [target, 1, 2, 3, 4, 5] = if(target==1)2;if(target==3)4;else5;
 * [target, 1, 2, 3, 4] = if(target==1)2;if(target==3)4;else target;
 * @author sam Created on 2011-4-12
 */
@Component
public class Decode implements DataHandler<Object> {
	private static NumberEqual numberEqual=new NumberEqual();

	@Override
	public Object handle(List<Object> argList) throws FunctionException {
		Object target=argList.get(0);
		Object defaultValue;
		if(argList.size()%2==1) {
			defaultValue = null;
		} else {
			defaultValue = argList.get(argList.size()-1);
		}
		for (int i = 2; i < argList.size(); i+=2) {
			if(eq(target, argList.get(i-1))) {
				return argList.get(i);
			}
		}
		if(defaultValue==null) {
			return target;
		} else {
			return defaultValue;
		}
	}

	public static boolean eq(Object target, Object object) {
		if(target==null) {
			if(object==null) {
				return true;
			} else {
				return false;
			}
		} else if(target.equals(object)) {
			return true;
		} else if(target instanceof Number && object instanceof Number) {
			return numberEqual.handle(Arrays.asList(target, object));
		} else {
			return false;
		}
	}

	@Override
	public void validate(List<FunctionArgument> arguments) throws FunctionException {
		if(arguments == null || arguments.size() < 3) {
			throw new FunctionException("Datahandler: " + this.getClass() + ", at least 3 argument");
		}
	}
}
class NumberEqual extends NumberOperater<Boolean> {

	@Override
	protected Boolean handleDouble(double value1, double value2) {
		return value1 == value2;
	}

	@Override
	protected Boolean handleInteger(int value1, int value2) {
		return value1 == value2;
	}

	@Override
	protected Boolean handleLong(long value1, long value2) {
		return value1 == value2;
	}

}
